<?php
/**
 * User abstraction.
 *
 * @category Zend
 * @package User
 * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc.
 * @version $Id$
 * @link http://framework.zend.com
 * @since Available since release 1.0
 * @license GPL v3
 */

class Application_Model_User extends Disputeo_Model_Abstract
{
    /**
     * @var Application_Model_DbTable_UserInfo
     */
    protected $_info;
    
    /**
     * Set table and row objects
     * 
     * @param array $options 
     */
    public function __construct($options = array())
    {
        $this->setTable(new Application_Model_DbTable_User());
        $this->setAttributes($options);
        
        $this->_info = new Application_Model_DbTable_UserInfo();
    }
    
    /**
     * Create a new user
     * 
     * @param array $data
     * @return self 
     */
    public static function create(array $data)
    {
        $user = new self();
        $user->_add($data);
        
        return $user;
    }
    
    /**
     * Get a user
     * 
     * @param type $id
     * @return self 
     */
    public static function get($id)
    {
        $user = new self();
        $user->_find($id);
        
        return $user;
    }
    
    /**
     * Add a user to DB
     * 
     * @param array $data
     * @return Application_Model_User
     */
    protected function _add(array $data)
    {
        $attributes = $this->_saltPassword($data);
        $email = isset($attributes['email']) ? $attributes['email'] : null;
        unset($attributes['email']);
        
        $userId = $this->_table->insert($attributes);
        
        if ($email) {
            $this->_info->insert(array(
                'userId' => $userId,
                'email' => $data['email']
            ));
        }
        
        return $this->_find($userId);
    }
    
    /**
     * Salt the password and add the salt data
     * 
     * @param array $data
     * @return array
     */
    protected function _saltPassword(array $data)
    {
        $salt = '';
        for ($i = 0; $i < 50; $i++) {
            $salt .= chr(rand(33, 126));
        }
        $data['password'] = sha1($data['password'] . $salt);
        $data['passwordSalt'] = $salt;
        
        return $data;
    }
}

